package com.yunquan.ohana.ui.editProfile

import android.app.Application
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import cn.jpush.android.api.JPushInterface
import com.bumptech.glide.util.Util
import com.google.gson.Gson
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.base.bus.event.SingleLiveEvent
import com.yunquan.ohana.base.ui.AppManager
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.entity.EventType
import com.yunquan.ohana.entity.FileEntity
import com.yunquan.ohana.entity.UserManager
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.exception.ApiException
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.ui.bindDevice.BindDeviceActivity
import com.yunquan.ohana.ui.bindEmail.BindEmailActivity
import com.yunquan.ohana.ui.editProfile.dialog.DeleteDialog
import com.yunquan.ohana.ui.editProfile.dialog.LogoutDialog
import com.yunquan.ohana.ui.login.LoginActivity
import com.yunquan.ohana.utils.SPUtils
import com.yunquan.ohana.utils.StringUtils
import com.yunquan.ohana.utils.ToastUtils
import com.yunquan.ohana.utils.Utils
import io.reactivex.rxjava3.disposables.Disposable
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File

class EditProfileViewModel(application: Application) : BaseViewModel(application) {

    val ui = SingleLiveEvent<Int>()

    val mEmail = ObservableField<String>()

    val onAvatarClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            ui.value = 0
        }
    })
    val onNickNameClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            ui.value = 1
        }
    })
    val onEmailClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            startActivity(BindEmailActivity::class.java)
        }
    })
    val onLogOutClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val dialog = LogoutDialog(AppManager.appManager.currentActivity()!!)
            dialog.setOnCheckedListener {
                logout()
            }
            dialog.show()
        }
    })
    val onDeleteAccountClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val dialog = DeleteDialog(AppManager.appManager.currentActivity()!!)
            dialog.setOnCheckedListener {
                deleteUser()
            }
            dialog.show()
        }
    })

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        mEmail.set(UserManager.instance.getUser()?.email)
    }

    override fun onEvent(event: EventEntity) {
        super.onEvent(event)
        if (event.type == EventType.UPDATE_EMAIL) {
            val email = event.data as String
            mEmail.set(email)
        }
    }

    private fun logout() {
        SPUtils.remove("userId")
        SPUtils.remove("token")
        UserManager.instance.clear()
        JPushInterface.stopPush(Utils.instance.context)
        AppManager.appManager.AppExit()
        startActivity(BindDeviceActivity::class.java)
    }

    fun uploadAvatar(file: File) {
        val body = file.asRequestBody("multipart/form-data".toMediaType())
        val part = MultipartBody.Part.createFormData("file", file.name, body)
        BaseHttp.api.uploadFile(1, part)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<FileEntity>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: FileEntity?) {
                    super.onSuccess(result)
                    if (result == null) {
                        hideLoading()
                        return
                    }
                    updateUserInfo(null, result)
                }

                override fun onError(e: ApiException) {
                    super.onError(e)
                    hideLoading()
                }
            })

    }

    fun updateUserInfo(nickname: String?, avatar: FileEntity?) {
        val params = mutableMapOf<String, String>()
        if (!StringUtils.isEmpty(nickname)) {
            params["nickname"] = nickname!!
        }
        if (avatar?.id != null) {
            params["headImg"] = avatar.id
        }
        val json = Gson().toJson(params)
        val body = json.toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.updateAppUser(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Boolean>() {

                override fun onSuccess(result: Boolean?) {
                    super.onSuccess(result)
                    if (result == true) {
                        if (!StringUtils.isEmpty(nickname)) {
                            UserManager.instance.setNickname(nickname!!)
                        }
                        if (avatar?.fileUrl != null) {
                            UserManager.instance.setAvatar(avatar.fileUrl)
                        }
                        RxBus.getDefault().post(EventEntity(EventType.UPDATE_USER))
                    }
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }

    private fun deleteUser() {
        BaseHttp.api.deleteUser()
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Boolean>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: Boolean?) {
                    super.onSuccess(result)
                    if (result == true) {
                        logout()
                    }else{
                        ToastUtils.showShort(Utils.instance.getString(R.string.failure_to_logout))
                    }
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }
}